class Solution(object):
    def nextGreaterElement(self, n):
        num = str(n)
        m = len(num)
        if m == 1:
            return -1
        index = m - 2
        while index >= 0:
            if num[index] < num[index + 1]:
                break
            else:
                index -= 1
        if index == -1:
            return -1
        right_index = index + 2
        right_min = index + 1
        while right_index < m:
            if num[index] < num[right_index] < num[right_min]:
                right_min = right_index
            right_index += 1
        right_t = list(num[index:right_min] + num[right_min + 1:])
        right_t.sort()
        new_num = int(num[:index] + num[right_min] + ''.join(right_t))
        if new_num > 2 ** 31 - 1:
            return - 1
        else:
            return new_num


